


package jnpf.zc.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.engine.enums.FlowStatusEnum;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.permission.entity.UserEntity;
import jnpf.util.GeneraterSwapUtil;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import jnpf.zc.entity.ZcglZcdjInfoChangeEntity;
import jnpf.zc.entity.ZcglZcdjInfoEntity;
import jnpf.zc.mapper.ZcglZcdjInfoMapper;
import jnpf.zc.model.zcglzcdjinfochange.ZcglZcdjInfoChangeForm;
import jnpf.zc.model.zcglzcdjinfochange.ZcglZcdjInfoChangeInfoVO;
import jnpf.zc.model.zcglzcdjinfochange.ZcglZcdjInfoChangeListVO;
import jnpf.zc.model.zcglzcdjinfochange.ZcglZcdjInfoChangePagination;
import jnpf.zc.service.ZcglZcdjInfoChangeService;
import jnpf.zc.service.ZcglZcdjInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * ZcglZcdjInfoChange
 *
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2024-12-29
 */
@Slf4j
@RestController
@Api(tags = "ZcglZcdjInfoChange", value = "example")
@RequestMapping("/api/example/ZcglZcdjInfoChange")
public class ZcglZcdjInfoChangeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;


    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ZcglZcdjInfoChangeService zcglZcdjInfoChangeService;

    @Autowired
    private ZcglZcdjInfoService zcglZcdjInfoService;
    @Autowired
    private ZcglZcdjInfoMapper zcdjInfoMapper;


    /**
     * 列表
     *
     * @param zcglZcdjInfoChangePagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcglZcdjInfoChangePagination zcglZcdjInfoChangePagination) throws IOException {
        List<ZcglZcdjInfoChangeEntity> list = zcglZcdjInfoChangeService.getList(zcglZcdjInfoChangePagination);
        //处理id字段转名称，若无需转或者为空可删除
        List<ZcglZcdjInfoChangeListVO> listVO = JsonUtil.getJsonToList(list, ZcglZcdjInfoChangeListVO.class);
        for (ZcglZcdjInfoChangeListVO zcglZcdjInfoChangeVO : listVO) {
            zcglZcdjInfoChangeVO.setCreatoruserid_name(zcglZcdjInfoChangeVO.getCreatoruserid());

//                zcglZcdjInfoChangeVO.setOlddata_name(zcglZcdjInfoChangeVO.getOldData());
//
//                zcglZcdjInfoChangeVO.setNewData_name(zcglZcdjInfoChangeVO.getNewData());


            //子表数据转换
        }

        for (ZcglZcdjInfoChangeListVO vo : listVO) {
            FlowTaskEntity flowTaskEntity = generaterSwapUtil.getInfoSubmit(vo.getId(), FlowTaskEntity::getStatus);
            if (flowTaskEntity != null) {
                vo.setFlowState(flowTaskEntity.getStatus());
            } else {
                vo.setFlowState(null);
            }

            ZcglZcdjInfoEntity info = zcglZcdjInfoService.getInfo(vo.getZcdgId());
            if (ObjectUtil.isNotEmpty(info)) {
                String zcName = info.getZcName();
                vo.setZcName(zcName);
            }


        }
        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcglZcdjInfoChangePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param crData
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody Map<String, Object> crData) throws DataException {
        ZcglZcdjInfoChangeForm zcglZcdjInfoChangeForm = JsonUtil.getJsonToBean(crData, ZcglZcdjInfoChangeForm.class);
        zcglZcdjInfoChangeForm.setNewData(JSONUtil.toJsonStr(crData.get("newData")));
        boolean b = zcglZcdjInfoChangeService.checkForm(zcglZcdjInfoChangeForm, 0);

        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String visualId = "643082324031848005";
        if (zcglZcdjInfoChangeForm.getType().equals("2")) {
            visualId = "643082324031848006";
        }
        if (zcglZcdjInfoChangeForm.getType().equals("1")) {
            visualId = "643082324031848005";
        }
        if (zcglZcdjInfoChangeForm.getType().equals("3")) {
            visualId = "643082324031848007";
        }
        //照片
        if (zcglZcdjInfoChangeForm.getType().equals("4")) {
            visualId = "6430823240318480071";
        }
        if (zcglZcdjInfoChangeForm.getType().equals("5")) {
            visualId = "643082324031848009";
        }
        if (zcglZcdjInfoChangeForm.getType().equals("6")) {
            visualId = "643082324031848008";
        }

        VisualdevEntity visualdevEntity = generaterSwapUtil.getVisualEntity(visualId);
        String mainId = RandomUtil.uuId();
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcglZcdjInfoChangeEntity entity = JsonUtil.getJsonToBean(zcglZcdjInfoChangeForm, ZcglZcdjInfoChangeEntity.class);
        entity.setId(mainId);
        entity.setCreatortime(new Date());
        entity.setCreatoruserid(userEntity.getId());

        String newData = entity.getNewData();
        boolean jsonArrayBo = this.isJsonArray(newData);
        if(jsonArrayBo){
            List<ZcglZcdjInfoEntity> zcglZcdjInfoEntitys = JsonUtil.getJsonToList(newData, ZcglZcdjInfoEntity.class);
            if(IterUtil.isNotEmpty(zcglZcdjInfoEntitys)){
                for (ZcglZcdjInfoEntity zcglZcdjInfoEntity:zcglZcdjInfoEntitys){
                    List<ZcglZcdjInfoEntity> zcdjInfoEntities = zcdjInfoMapper.selectList(new QueryWrapper<ZcglZcdjInfoEntity>()
                            .eq("ZC_NUMBER", zcglZcdjInfoEntity.getZcNumber())
                    );
                    if (IterUtil.isNotEmpty(zcdjInfoEntities)) {
                        throw new DataException("资产编号已存在");
                    }
                }
            }
            String zcdgId = entity.getZcdgId();
            if(StrUtil.isNotEmpty(zcdgId)){
                String[] array = zcdgId.split(",");
                List<String> list = Stream.of(array)
                        .collect(Collectors.toList());
                List<ZcglZcdjInfoEntity> zcglZcdjInfoEntities = zcdjInfoMapper.selectBatchIds(list);
                String zcnames = zcglZcdjInfoEntities.stream()
                        .map(ZcglZcdjInfoEntity::getZcName)  // 提取zcName字段
                        .collect(Collectors.joining(","));  // 用逗号拼接
                entity.setZcName(zcnames);
            }
        }

        zcglZcdjInfoChangeService.save(entity);

        if (FlowStatusEnum.submit.getMessage().equals(zcglZcdjInfoChangeForm.getStatus())) {
            try {
                if (crData.get("title") != null) {
                    visualdevEntity.setFullName(crData.get("title").toString());
                }
                generaterSwapUtil.submitFlowTask(visualdevEntity, mainId, zcglZcdjInfoChangeForm, userInfo, zcglZcdjInfoChangeForm.getCandidateList(), zcglZcdjInfoChangeForm.getFlowUrgent());
            } catch (WorkFlowException e) {
                e.printStackTrace();
            }
            return ActionResult.success("提交成功，请耐心等待");
        }
        return ActionResult.success("保存成功");
    }

    // 判断是否是 JSON 数组
    public static boolean isJsonArray(String jsonString) {
        try {
            new JSONArray(jsonString);  // 尝试将字符串解析为 JSON 数组
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcglZcdjInfoChangeInfoVO> info(@PathVariable("id") String id) {
        ZcglZcdjInfoChangeEntity entity = zcglZcdjInfoChangeService.getInfo(id);
        ZcglZcdjInfoChangeInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglZcdjInfoChangeInfoVO.class);

        //子表
        //副表
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param upData
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid Map<String, Object> upData) throws DataException {
        ZcglZcdjInfoChangeForm zcglZcdjInfoChangeForm = JsonUtil.getJsonToBean(upData, ZcglZcdjInfoChangeForm.class);
        boolean b = zcglZcdjInfoChangeService.checkForm(zcglZcdjInfoChangeForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String visualId = "643082324031848005";
        VisualdevEntity visualdevEntity = generaterSwapUtil.getVisualEntity(visualId);
        UserInfo userInfo = userProvider.get();
        ZcglZcdjInfoChangeEntity entity = zcglZcdjInfoChangeService.getInfo(id);
        if (entity != null) {
            ZcglZcdjInfoChangeEntity subentity = JsonUtil.getJsonToBean(zcglZcdjInfoChangeForm, ZcglZcdjInfoChangeEntity.class);
            boolean b1 = zcglZcdjInfoChangeService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            if (FlowStatusEnum.submit.getMessage().equals(zcglZcdjInfoChangeForm.getStatus())) {
                try {
                    generaterSwapUtil.submitFlowTask(visualdevEntity, id, subentity, userInfo, zcglZcdjInfoChangeForm.getCandidateList(), zcglZcdjInfoChangeForm.getFlowUrgent());
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
                return ActionResult.success("提交成功，请耐心等待");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcglZcdjInfoChangeEntity entity = zcglZcdjInfoChangeService.getInfo(id);
        if (entity != null) {
            FlowTaskEntity taskEntity = generaterSwapUtil.getInfoSubmit(id, FlowTaskEntity::getId, FlowTaskEntity::getStatus);
            if (taskEntity != null) {
                try {
                    generaterSwapUtil.deleteFlowTask(taskEntity);
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
            }
            zcglZcdjInfoChangeService.delete(entity);

        }
        return ActionResult.success("删除成功");
    }


}
